package com.hhq.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Date;


/**
 * <p>Description: 通用字段填充器 </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/1/5 15:33
 */
@Component
public class CommonFieldMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATE_USER = "createUser";

    private static final String CREATE_USER_NAME = "createUserName";

    private static final String CREATE_TIME = "createTime";

    private static final String UPDATE_USER = "updateUser";

    private static final String UPDATE_USER_NAME = "updateUserName";

    private static final String UPDATE_TIME = "updateTime";

    private static final String DELETED = "deleted";


    @Override
    public void insertFill(MetaObject metaObject) {

        if (isValue(CREATE_TIME, metaObject)) {
            setFieldValByName(CREATE_USER, new Date(), metaObject);
        }
        if (isValue(UPDATE_TIME, metaObject)) {
            setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        }
        if (isValue(DELETED, metaObject)) {
            setFieldValByName(DELETED, false, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (isValue(UPDATE_TIME, metaObject)) {
            setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        }
    }


    /**
     * 判断值是否为空
     *
     * @param filedName  字段名称
     * @param metaObject
     * @return 元数据
     */
    private boolean isValue(String filedName, MetaObject metaObject) {
        // 值是否存在
        boolean value = metaObject.hasGetter(filedName);
        // 字段存在，值为空
        if (value && ObjectUtils.isEmpty(metaObject.getValue(filedName))) {
            return true;
        }
        return false;
    }
}
